﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Text;
using System.Text.RegularExpressions;

public partial class Centers : System.Web.UI.Page
{
    protected string sTitle=string.Empty;
    private int iTotalPages = 0;
    private int iPageSize = 4;
    public int CurrentPage = 1;
    private string sCategory =string.Empty;

    protected void Page_Load(object sender, EventArgs e)
    {

        GetParameters();

        // Hightlight main menu
        ucHeader1.index = "4";
        
        CategoryItem catItem = Category.ItemById((int)NewsType.MedicalCenters);
        this.Title = catItem.cTitle;

        if (sCategory.Length == 0)
        {
            HtmlMeta meta = new HtmlMeta();
            meta.Name = "keywords";
            meta.Content = PageHeaderData.GetPageKeywordsByType(NewsType.MedicalCenters);
            this.Header.Controls.Add(meta);
            
            meta = new HtmlMeta();
            meta.Name = "descriprion";
            meta.Content = Category.ItemById((int)NewsType.MedicalCenters).cDescription;
            this.Header.Controls.Add(meta);

            divContacts.Visible = true;
            List<CategoryItem> cat = Category.ByAncestors((int)NewsType.MedicalCenters);
            if (cat != null)
            {
                string sulString = string.Empty;
                foreach (CategoryItem item in cat)
                {
                    sulString = string.Format("<li><a href=\"{0}-c.aspx\">{1}</a></li>", HttpUtility.UrlEncode(item.cPageName), item.cTitle);
                    ulCenters.InnerHtml += sulString;
                }
            }
        }
        else
        {
            divTitle.Visible = true;
        }

        GetNewsData();
    }

    private void GetParameters()
    {
        //CurrentPage = Math.Abs(Convert.ToInt32((Request.Params["page"] == string.Empty) ? "1" : Request.Params["page"]));
        
        sCategory = (Request.Params["category"] == null) ? string.Empty : Request.Params["category"].ToString();
        if (sCategory.Length > 0)
        {
            string sPage =string.Empty;
            try
            {
                sPage = sCategory.Split('^')[1];
                Regex rx=new Regex(@"([\d]*)");
                Match m=rx.Match(sPage);
                if(m.Success)
                {
                    int.TryParse(Regex.Replace(sPage,@"[^\d]",""),out CurrentPage);
                }
            }
            catch { }
            sCategory = sCategory.Split('^')[0];
            if (sCategory.ToLower() == "centers")
                sCategory = string.Empty;
        }
    }

    private void GetNewsData()
    {
        if (sCategory.Length == 0)
        {
            Dal.arParams.Clear();
            Dal.arParams.Add((int)NewsType.MedicalCenters);//CatID
            Dal.arParams.Add(CurrentPage);//Current Page
            Dal.arParams.Add(iPageSize);//PageSize
            DataTable DT = Dal.ExecuteDBsp("usp_GetMedicalCentersWPaging", Dal.arParams);
            if (DT != null)
            {
                if (DT.Rows.Count > 0)
                {
                    iTotalPages = (int)Math.Ceiling((double)Convert.ToInt32(DT.Rows[0]["TotalRows"]) / iPageSize);
                    
                    gvNews.DataSource = DT;
                    gvNews.DataBind();

                    SimplePager();
                }
            }
        }
        else
        {
            CategoryItem cItem= Category.ItemByPageName(sCategory);
            HtmlMeta meta = new HtmlMeta();
            meta.Name = "keywords";
            meta.Content = PageHeaderData.GetPageKeywordsByCatID(cItem.catId);
            this.Header.Controls.Add(meta);

            meta = new HtmlMeta();
            meta.Name = "descriprion";
            meta.Content = cItem.cDescription;
            this.Header.Controls.Add(meta);

            sTitle = cItem.cTitle;
            Dal.arParams.Clear();
            Dal.arParams.Add(cItem.catId);//CatID
            Dal.arParams.Add(CurrentPage);//Current Page
            Dal.arParams.Add(iPageSize);//PageSize
            DataTable DT = Dal.ExecuteDBsp("usp_GetNewsByCategoryWPaging", Dal.arParams);
            if (DT != null)
            {
                if (DT.Rows.Count > 0)
                {
                    iTotalPages = (int)Math.Ceiling((double)Convert.ToInt32(DT.Rows[0]["TotalRows"]) / iPageSize);
                    gvNews.DataSource = DT;
                    gvNews.DataBind();

                    SimplePager();
                }
            }
        }
    }

    public void SimplePager()
    {
        if (CurrentPage < 0) CurrentPage = 1;
        if (iTotalPages < 0) iTotalPages = 0;

        var pager = new PagerBuilder(sCategory);

        if (CurrentPage > 1)
        {
            pager.AddPage("&lt;&lt;", 1);
            pager.AddPage("&lt;", CurrentPage - 1);
        }

        var start = Math.Max(CurrentPage - 2, 1);
        var end = Math.Min(iTotalPages, CurrentPage + 2);

        for (var i = start; i <= end; i++)
        {
            if (i == CurrentPage)
                pager.AddPage(i.ToString(), i, "font-weight: bold; color: #0b61a4;");
            else
                pager.AddPage(i.ToString(), i);
        }

        if (CurrentPage < iTotalPages)
        {
            pager.AddPage("&gt;", CurrentPage + 1);
            pager.AddPage("&gt;&gt;", iTotalPages);
        }

        nav6.InnerHtml += pager.ToString();
    }

    public class PagerBuilder
    {
        private class PagerLink
        {
            public string Title { get; set; }
            public int PageNo { get; set; }
            public string Class { get; set; }
        }

        private readonly string sCategory;
        private readonly List<PagerLink> _pagerLinks =
                new List<PagerLink>();

        public PagerBuilder(string sCategory)
        {
            this.sCategory = sCategory;
        }

        public string PagerClass { get; set; }

        public void AddPage(string title, int pageNo)
        {
            AddPage(title, pageNo, string.Empty);
        }

        public void AddPage(string title, int pageNo,
                            string itemClass)
        {
            var link = new PagerLink
            {
                PageNo = pageNo,
                Title = title,
                Class = itemClass
            };
            _pagerLinks.Add(link);
        }

        public override string ToString()
        {
            var builder = new StringBuilder();

            foreach (var link in _pagerLinks)
            {
                builder.Append("<li>");
                builder.Append("<a");
                if (link.Class != string.Empty)
                {
                    builder.AppendFormat(" style=\"{0}\"", link.Class);
                }
                builder.Append(" href=\"");
                if (sCategory .Length == 0)
                    builder.AppendFormat("centers^p_{0}-c.aspx", link.PageNo);
                else
                    builder.AppendFormat("{0}^p_{1}-c.aspx",sCategory, link.PageNo);
                builder.Append("\">");
                builder.Append(link.Title);
                builder.Append("</a>");
                builder.Append("</li>");
            }
            return builder.ToString();
        }
    }
}
